<template>
  <div class="exercise-library-container">
    <div class="page-header glass-card">
      <h1>动作库</h1>
      <div class="search-bar">
        <input type="text" v-model="searchQuery" placeholder="搜索动作...">
        <button class="search-btn">🔍</button>
      </div>
    </div>

    <!-- 分类筛选 -->
    <div class="category-filter glass-card">
      <button 
        v-for="category in categories"
        :key="category.id"
        :class="{ active: selectedCategory === category.id }"
        @click="selectCategory(category.id)"
      >
        {{ category.name }}
      </button>
    </div>

    <!-- 动作列表 -->
    <div class="exercises-grid">
      <div class="card-wrap" 
  v-for="exercise in filteredExercises"
  :key="exercise.id"
  @mousemove="handleMouseMove"
  @mouseenter="handleMouseEnter"
  @mouseleave="handleMouseLeave"
  @click="openExerciseDetail(exercise)"
  :ref="el => cardRefs.push(el)">
  <div class="card" :style="cardStyle">
    <div class="card-bg" :style="[cardBgTransform, { backgroundImage: `url(${exercise.image})` }]"></div>
    <div class="card-info">
      <h3>{{ exercise.name }}</h3>
      <div class="exercise-meta">
        <span class="muscle-group">{{ exercise.muscleGroup }}</span>
        <span class="difficulty" :class="exercise.difficulty.toLowerCase()">
          {{ exercise.difficulty }}
        </span>
      </div>
    </div>
  </div>
</div>
    </div>

    <!-- 动作详情模态框 -->
    <div v-if="selectedExercise" class="modal-overlay" @click="closeExerciseDetail">
      <div class="modal-content glass-card" @click.stop>
        <button class="close-btn" @click="closeExerciseDetail">×</button>
        <div class="modal-header">
          <img :src="selectedExercise.image" :alt="selectedExercise.name" class="detail-image">
          <div class="detail-header-info">
            <h2>{{ selectedExercise.name }}</h2>
            <div class="detail-meta">
              <span class="muscle-group">{{ selectedExercise.muscleGroup }}</span>
              <span class="difficulty" :class="selectedExercise.difficulty.toLowerCase()">
                {{ selectedExercise.difficulty }}
              </span>
            </div>
          </div>
        </div>
        <div class="modal-body">
          <div class="instructions">
            <h3>动作说明</h3>
            <ol>
              <li v-for="(step, index) in selectedExercise.instructions" :key="index">
                {{ step }}
              </li>
            </ol>
          </div>
          <div class="tips">
            <h3>小贴士</h3>
            <p>{{ selectedExercise.tips }}</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-primary" @click="addExerciseToWorkout">添加到训练</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useWorkoutStore } from '@/stores/workout';

const cardRefs = ref([]);
const mouseX = ref(0);
const mouseY = ref(0);
const mouseLeaveDelay = ref(null);
const cardWidth = ref(240);
const cardHeight = ref(320);

const cardStyle = computed(() => {
  const rX = (mouseX.value / cardWidth.value) * 30;
  const rY = (mouseY.value / cardHeight.value) * -30;
  return { transform: `rotateY(${rX}deg) rotateX(${rY}deg)` };
});

const cardBgTransform = computed(() => {
  const tX = (mouseX.value / cardWidth.value) * -40;
  const tY = (mouseY.value / cardHeight.value) * -40;
  return { transform: `translateX(${tX}px) translateY(${tY}px)` };
});

const handleMouseMove = (e) => {
  const rect = e.currentTarget.getBoundingClientRect();
  mouseX.value = e.clientX - rect.left - cardWidth.value/2;
  mouseY.value = e.clientY - rect.top - cardHeight.value/2;
};

const handleMouseEnter = () => {
  clearTimeout(mouseLeaveDelay.value);
};

const handleMouseLeave = () => {
  mouseLeaveDelay.value = setTimeout(() => {
    mouseX.value = 0;
    mouseY.value = 0;
  }, 1000);
};

onMounted(() => {
  // 初始化卡片尺寸
  if (cardRefs.value.length) {
    const rect = cardRefs.value[0].getBoundingClientRect();
    cardWidth.value = rect.width;
    cardHeight.value = rect.height;
  }
});

const workoutStore = useWorkoutStore();

// 搜索和筛选状态
const searchQuery = ref('');
const selectedCategory = ref('all');
const selectedExercise = ref(null);

// 分类数据
const categories = ref([
  { id: 'all', name: '全部' },
  { id: 'upper', name: '上肢' },
  { id: 'lower', name: '下肢' },
  { id: 'core', name: '核心' },
  { id: 'cardio', name: '有氧' },
  { id: 'flex', name: '柔韧性' }
]);

// 动作数据
const exercises = ref([
  { 
    id: 1, 
    name: '哑铃卧推', 
    muscleGroup: '胸部', 
    difficulty: '中级',
    category: 'upper',
    image: 'Image/20.jpg',
    instructions: [
      '平躺于卧推凳上，双脚平放地面',
      '双手握住哑铃，与肩同宽，手臂伸直',
      '缓慢下降哑铃至胸部上方',
      '推起哑铃回到起始位置，注意肘部不要完全锁死'
    ],
    tips: '保持核心收紧，避免腰部过度拱起。控制动作速度，感受胸肌发力。'
  },
  { 
    id: 2, 
    name: '深蹲', 
    muscleGroup: '腿部', 
    difficulty: '初级',
    category: 'lower',
    image: 'Image/21.webp',

    instructions: [
      '双脚与肩同宽站立，脚尖略微向外',
      '双臂前伸保持平衡',
      '弯曲膝盖，臀部向后坐，仿佛要坐到椅子上',
      '下蹲至大腿与地面平行，然后推起回到起始位置'
    ],
    tips: '保持胸部挺起，膝盖与脚尖方向一致，不要内扣。重量应放在脚跟上。'
  },
  { 
    id: 3, 
    name: '平板支撑', 
    muscleGroup: '核心', 
    difficulty: '初级',
    category: 'core',
    image: 'Image/24.jpg',

    instructions: [
      '俯卧，前臂和脚尖支撑身体',
      '保持身体成一条直线，不要塌腰或撅臀',
      '收紧腹部和臀部肌肉',
      '保持均匀呼吸，坚持指定时间'
    ],
    tips: '初学者可以膝盖着地简化动作。每次坚持时间逐渐增加，目标30-60秒。'
  },
  { 
    id: 4, 
    name: '俯卧撑', 
    muscleGroup: '胸部/手臂', 
    difficulty: '中级',
    category: 'upper',
    image: 'Image/4.jpg',

    instructions: [
      '俯卧，双手略宽于肩支撑身体',
      '保持身体成一条直线，核心收紧',
      '弯曲肘部下降身体，胸部接近地面',
      '推起身体回到起始位置'
    ],
    tips: '如果标准俯卧撑太难，可以膝盖着地或抬高手部位置。注意肘部不要过度外展。'
  },
  { 
    id: 5, 
    name: '弓步', 
    muscleGroup: '腿部', 
    difficulty: '初级',
    category: 'lower',
    image: 'Image/23.jpg',

    instructions: [
      '直立站立，双脚并拢',
      '向前跨出一大步，下蹲直到前腿膝盖成90度角',
      '后腿膝盖接近地面但不要接触',
      '推起身体回到起始位置，然后换腿'
    ],
    tips: '保持上身挺直，前膝不要超过脚尖。可以在手中持哑铃增加难度。'
  },
  { 
    id: 6, 
    name: '仰卧卷腹', 
    muscleGroup: '腹部', 
    difficulty: '初级',
    category: 'core',
    image: 'Image/6.jpg',

    instructions: [
      '仰卧，膝盖弯曲，双脚平放地面',
      '双手交叉放在胸前或耳侧（不要拉头部）',
      '收紧腹部，缓慢抬起上背部离开地面',
      '停顿一秒后缓慢下降回到起始位置'
    ],
    tips: '专注于腹部肌肉收缩，避免用手拉头部或借助惯性。动作要缓慢有控制。'
  }
]);

// 筛选动作
const filteredExercises = computed(() => {
  return exercises.value.filter(exercise => {
    const matchesSearch = exercise.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                         exercise.muscleGroup.toLowerCase().includes(searchQuery.value.toLowerCase());
    const matchesCategory = selectedCategory.value === 'all' || exercise.category === selectedCategory.value;
    return matchesSearch && matchesCategory;
  });
});

// 方法
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId;
};

const openExerciseDetail = (exercise) => {
  selectedExercise.value = exercise;
  document.body.style.overflow = 'hidden'; // 防止背景滚动
};

const closeExerciseDetail = () => {
  selectedExercise.value = null;
  document.body.style.overflow = ''; // 恢复背景滚动
};

const addExerciseToWorkout = () => {
  if (selectedExercise) {
    workoutStore.addExerciseToCurrentWorkout(selectedExercise);
    alert(`${selectedExercise.name} 已添加到当前训练计划！`);
    closeExerciseDetail();
  }
};
</script>

<style scoped lang="scss">
$hoverEasing: cubic-bezier(0.23, 1, 0.32, 1);
$returnEasing: cubic-bezier(0.445, 0.05, 0.55, 0.95);

.exercise-library-container {
  --safe-area-top: env(safe-area-inset-top);
  --viewport-height: 100dvh; /* 使用动态视口高度 */
  --header-height: 80px;
  --footer-height: 92px;
  

  max-width: 100%;
  margin: 0 auto;
  padding: calc(var(--header-height) + var(--safe-area-top)) 0 var(--footer-height);
  min-height: calc(var(--viewport-height) - var(--safe-area-top) - var(--header-height) - var(--footer-height));
  position: relative;
  z-index: 1;
  overflow-y: auto;
  font-family: "Raleway";
  font-size: 14px;
  font-weight: 500;

  -webkit-font-smoothing: antialiased;
}

.title {
  font-family: "Raleway";
  font-size: 24px;
  font-weight: 700;
  color: white !important;
  text-align: center;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;

  h1 {
    color: white;
  }
}

.search-bar {
  display: flex;
  width: auto;
  min-width: 250px;
}

.search-bar input {
  &::placeholder { color: white; opacity: 0.7; }
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  background-color: #fff;
  outline: none;
  transition: border-color 0.3s;
}

.search-bar input:focus {
  border-color: #5D4037;
}

.search-btn {
  color: white;
  background-color: #5D4037;
  border: none;
  padding: 0 15px;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-btn:hover {
  background-color: #3E2723;
}

.category-filter {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  overflow-x: auto;
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5));
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.category-filter button {
  padding: 5px 15px;
  border: none;
  border-radius: 20px;
  background-color: rgba(255,255,255,0.2);
  color: white;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s $hoverEasing;

  &.active {
    background-color: #5D4037;
    color: white;
  }

  &:hover {
    background-color: rgba(255,255,255,0.3);
  }
}

.exercises-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 4vw;
    padding: 0 2vw;
    
    .card-wrap {
      width: 100%;
      margin: 2vw 0;
      transform: none;
      .card {
        width: 92vw;
        height: 60vw;
        margin: 0 auto;
      }
      .card-info h3 {
        font-size: clamp(1.2rem, 4vw, 1.5rem);
      }
    }
    
    .exercise-meta {
      flex-direction: column;
      gap: 1vw;
    }
  }
}

.card-wrap {
  margin: 10px;
  transform: perspective(800px);
  transform-style: preserve-3d;
  cursor: pointer;

  &:hover {
    .card-info {
      transform: translateY(0);
    }
    .card-info p {
      opacity: 1;
    }
    .card-info, .card-info p {
      transition: 0.6s $hoverEasing;
    }
    .card-info:after {
      transition: 5s $hoverEasing;
      opacity: 1;
      transform: translateY(0);
    }
    .card-bg {
      transition: 0.6s $hoverEasing, opacity 5s $hoverEasing;
      opacity: 0.8;
    }
    .card {
      transition: 0.6s $hoverEasing, box-shadow 2s $hoverEasing;
      box-shadow: rgba(255, 255, 255, 0.2) 0 0 40px 5px, rgba(255, 255, 255, 1) 0 0 0 1px, rgba(0, 0, 0, 0.66) 0 30px 60px 0, inset #333 0 0 0 5px, inset white 0 0 0 6px;
    }
  }
}

.card {
  position: relative;
  flex: 0 0 240px;
  width: 240px;
  height: 320px;
  background-color: #333;
  overflow: hidden;
  border-radius: 10px;
  box-shadow: rgba(black, 0.66) 0 30px 60px 0, inset #333 0 0 0 5px, inset rgba(white, 0.5) 0 0 0 6px;
  transition: 1s $returnEasing;
}

.card-bg {
  opacity: 0.5;
  position: absolute;
  top: -20px; left: -20px;
  width: 100%;
  height: 100%;
  padding: 20px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  transition: 1s $returnEasing, opacity 5s 1s $returnEasing;
  pointer-events: none;
}

.card-info {
  padding: 20px;
  position: absolute;
  bottom: 0;
  color: #fff;
  transform: translateY(40%);
  transition: 0.6s 1.6s cubic-bezier(0.215, 0.61, 0.355, 1);

  p {
    opacity: 0;
    text-shadow: rgba(black, 1) 0 2px 3px;
    transition: 0.6s 1.6s cubic-bezier(0.215, 0.61, 0.355, 1);
  }

  * {
    position: relative;
    z-index: 1;
  }

  &:after {
    content: '';
    position: absolute;
    top: 0; left: 0;
    z-index: 0;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.6) 100%);
    background-blend-mode: overlay;
    opacity: 0;
    transform: translateY(100%);
    transition: 5s 1s $returnEasing;
  }
}

.card-info h3 {
  font-family: "Playfair Display";
  font-size: 24px;
  font-weight: 700;
  text-shadow: rgba(black, 0.5) 0 10px 10px;
}

.muscle-group, .difficulty {
  color: white;
  text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}

.category-filter button:hover {
  background-color: var(--gray-200);
}

.category-filter button.active {
  background-color: var(--primary);
  color: var(--white);
}

/* 已合并到上方flex布局定义 */

.exercise-card {
  border-radius: var(--radius-lg);
  overflow: hidden;
  cursor: pointer;
  transition: transform var(--transition-normal), box-shadow var(--transition-normal);
  background-color: var(--white);
  box-shadow: var(--shadow-md);
}

.exercise-card:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-lg);
}

.exercise-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.exercise-info {
  padding: var(--spacing-md);
}

.exercise-info h3 {
  margin-bottom: var(--spacing-xs);
  color: white;
  font-size: var(--font-size-base);
}

.exercise-meta {
  display: flex;
  justify-content: space-between;
  font-size: var(--font-size-sm);
}

.muscle-group {
  color: var(--gray-500);
}

.difficulty {
  padding: 0.2rem 0.5rem;
  border-radius: var(--radius-full);
  font-weight: var(--font-weight-medium);
  font-size: var(--font-size-sm);
}

.difficulty.初级 {
  background-color: rgba(0, 180, 42, 0.1);
  color: white;
}

.difficulty.中级 {
  background-color: rgba(255, 125, 0, 0.1);
  color: white;
}

.difficulty.高级 {
  background-color: rgba(245, 63, 63, 0.1);
  color: white;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-md);
  backdrop-filter: blur(4px);
}

.modal-content {
  width: 100%;
  max-width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  border-radius: var(--radius-xl);
  position: relative;
  background-color: var(--white);
  box-shadow: var(--shadow-xl);
  padding: var(--spacing-lg);
}

.close-btn {
  position: absolute;
  top: var(--spacing-md);
  right: var(--spacing-md);
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: white;
  z-index: 10;
  transition: color var(--transition-normal);
}

.close-btn:hover {
  color: white;
}

.modal-header {
  display: flex;
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-md);
  border-bottom: 1px solid var(--gray-200);
}

.detail-image {
  width: 30%;
  border-radius: var(--radius-lg);
  object-fit: cover;
  box-shadow: var(--shadow-md);
}

.detail-header-info {
  flex-grow: 1;
}

.detail-header-info h2 {
  color: white;
  margin-bottom: var(--spacing-xs);
  color: white;
  font-size: var(--font-size-xl);
}

.detail-meta {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-sm);
}

.modal-body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-md);
  max-height: 50vh;
  overflow-y: auto;
}

* {
  box-sizing: border-box;
}

.instructions h3,
.tips h3 {
  margin-bottom: var(--spacing-md);
  color: white;
  font-size: var(--font-size-lg);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.instructions h3::before,
.tips h3::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: var(--primary);
  border-radius: var(--radius-sm);
}

.instructions ol {
  color: white;
  padding-left: 1.5rem;
  line-height: 1.6;
  color: var(--gray-700);
  gap: var(--spacing-sm);
  display: flex;
  flex-direction: column;
}

.instructions li {
  position: relative;
  padding-left: var(--spacing-xs);
}

.tips p {
  color: white;
  line-height: 1.6;
  color: var(--gray-700);
  background-color: var(--gray-50);
  padding: var(--spacing-md);
  border-radius: var(--radius-md);
}

.modal-footer {
  text-align: right;
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--gray-200);
}

.btn-primary {
  color: white;
  background-color: var(--primary);
}

/* 动画效果 */
.exercises-grid {
  perspective: 1000px;
}

.exercise-card {
  animation: fadeIn 0.5s ease-out;
  animation-fill-mode: both;
}

.exercise-card:nth-child(1) { animation-delay: 0.1s; }
.exercise-card:nth-child(2) { animation-delay: 0.2s; }
.exercise-card:nth-child(3) { animation-delay: 0.3s; }
.exercise-card:nth-child(4) { animation-delay: 0.4s; }
.exercise-card:nth-child(5) { animation-delay: 0.5s; }
.exercise-card:nth-child(6) { animation-delay: 0.6s; }

.modal-content {
  animation: slideUp 0.3s ease-out;
}

@media (max-width: 768px) {
  .modal-header {
    flex-direction: column;
  }
  .detail-image {
    width: 100%;
    height: 200px;
  }
  .modal-body {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 400px) {
  .exercise-library-container {
    --viewport-height: 100dvh;
    --header-height: 15vw;
    --footer-height: 4vw;
    
    padding: calc(15vw + env(safe-area-inset-top)) 4vw calc(4vw + env(safe-area-inset-bottom));
    min-height: calc(var(--viewport-height) - env(safe-area-inset-top) - env(safe-area-inset-bottom));
    overflow-x: hidden;
  }

  /* 网格布局 */
  .exercises-grid {
    grid-template-columns: 1fr;
    gap: 3vw;
    padding: 0 2vw;
  }
  /* 分类筛选滚动 */
  .category-filter {
    flex-wrap: nowrap;
    gap: 3vw;
    padding: 2vw;
    margin: 0 2vw 3vw;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }

.category-filter button {
  padding: 0.4rem 0.6rem;
  font-size: 0.85rem;
  white-space: nowrap;
}
  /* 卡片尺寸 */
  .card-wrap {
    width: 96vw;
    margin: 2vw auto;
    transform: none;
  }
  /* 模态框适配 */
  .modal-content {
    width: 90vw;
    max-height: 80vh;
    padding: 4vw;
    border-radius: 4vw;
  }

.modal-header {
  flex-direction: column;
  align-items: flex-start;
}

.detail-image {
    max-width: 100%;
    height: 40vw;
    margin-bottom: 4vw;
    object-fit: cover;
  }
}
</style>